package thread.day2;

/**
 * 多线程的测试
 * 两个人:甲和乙分别往一个账户里面存钱,一次存一千
 *
 * @author wx
 * @create 2019-11-28 19:07
 */
public class MultiThreadDemo {

    public static void main(String[] args) {
        Account account = new Account();
        Customer customerA = new Customer(account, "用户A");
        Customer customerB = new Customer(account, "用户B");

        Thread t1 = new Thread(customerA);
        Thread t2 = new Thread(customerB);

        t1.start();
        t2.start();

    }


}

class Account {

    int money = 0;

    //同步方法一,synchronized 方法
//    public synchronized  void saveMoney(int saveMoney) {
//            lock.lock();
//            money += saveMoney;
//            System.out.println(Thread.currentThread().getName()+" 存入: "+saveMoney+",余额: "+money);
//    }
    //同步方法二:synchronized代码块
    public void saveMoney(int saveMoney) {
         synchronized (this){
            money += saveMoney;
            System.out.println(Thread.currentThread().getName()+" 存入: "+saveMoney+",余额: "+money);
        }
    }

    //同步方法三:ReentrantLock
//    public void saveMoney(int saveMoney) {
//        ReentrantLock lock = new ReentrantLock();
//        try {
//            lock.lock();
//            money += saveMoney;
//            System.out.println(Thread.currentThread().getName()+" 存入: "+saveMoney+",余额: "+money);
//        } finally {
//            lock.unlock();
//        }
//    }




}

class Customer implements Runnable {

    private Account account;

    public Customer(Account account, String ThreadName) {
        this.account = account;
        this.setThreadName(ThreadName);
    }

    //设置线程名称
    public void setThreadName(String ThreadName) {
        Thread.currentThread().setName(ThreadName);
    }

    //具体的存钱操作
    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.saveMoney(1000);
        }

    }
}
